package me.zhenqu.redis.utils;

import java.util.*;

public class CollectionUtils {
    public static <S, D> List<D> collect(Collection<S> source, Transformer<S, D> transformer) {
        if(source == null) return null;
        ArrayList<D> answer = new ArrayList<D>(source.size());
        collect(source, transformer, answer);
        return answer;
    }

    public static <S, D> List<D> collect(Collection<S> inputCollection,
                                         final Transformer<S, D> transformer,
                                         final List<D> outputCollection) {
        if (inputCollection != null) {
            return collect(inputCollection.iterator(), transformer, outputCollection);
        }
        return outputCollection;
    }

    public static <S, D> List<D> collect(Iterator<S> inputIterator,
                                         final Transformer<S, D> transformer,
                                         final List<D> outputCollection) {
        if (inputIterator != null && transformer != null) {
            while (inputIterator.hasNext()) {
                S item = inputIterator.next();
                D value = transformer.transform(item);
                outputCollection.add(value);
            }
        }
        return outputCollection;
    }

    public static <L, M> Map<L, M> toMap(Collection<M> source, Transformer<M, L> transformer) {
        if(source == null) return null;
        Map<L, M> answer = new HashMap<L, M>(source.size());
        for (M m : source) {
            answer.put(transformer.transform(m), m);
        }
        return answer;
    }

    public static <K, V> List<V> sort(Collection<K> seed, Collection<V> values, Transformer<V, K> transformer) {
        Map<K, V> kvMap = toMap(values, transformer);
        List<V> ret = new ArrayList<V>(seed.size());
        for (K k : seed) {
            V e = kvMap.get(k);
            if (e != null) {
                ret.add(e);
            }
        }
        return ret;
    }

    public static <K, V> List<V> sort(K[] seed, Collection<V> values, Transformer<V, K> transformer) {
        Map<K, V> kvMap = toMap(values, transformer);
        List<V> ret = new ArrayList<V>(seed.length);
        for (K k : seed) {
            V a = kvMap.get(k);
            if (a != null) {
                ret.add(a);
            }
        }
        return ret;
    }
}

